﻿using CqCore.Redis;
using SuperShopInfrastructure.Models.Area;
using SuperShopInfrastructure.Static;
using SuperShopRepository;
using SuperShopService.IServices;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace SuperShopService.Services
{
    public class AreaService : IAreaService
    {
        private readonly AreaRepository areaRepository;
        private readonly IRedisService redisService;

        public AreaService(
            AreaRepository areaRepository,
            IRedisService redisService)
        {
            this.areaRepository = areaRepository;
            this.redisService = redisService;
        }

        public async Task<List<AreaViewModel>> Get(int parentId)
        {
            var res = new List<AreaViewModel>();
            var ds = await areaRepository.GetArea(parentId);
            if (DataManager.CheckDs(ds, 1) && DataManager.CheckHasRow(ds.Tables[0]))
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    res.Add(new AreaViewModel()
                    {
                        Id = Convert.ToInt32(dr["Id"]),
                        Area_Code = Convert.ToInt32(dr["Area_Code"]),
                        Parent_Id = Convert.ToInt32(dr["Parent_Id"]),
                        Area_Name = dr["Area_Name"].ToString()
                    });
                }
            }
            return res;
        }

        public async Task<List<AreaViewModel>> GetAll()
        {
            var result = await redisService.GetOrSet<List<AreaViewModel>>("AllAreas", async () =>
            {
                var res = new List<AreaViewModel>();
                var ds = await areaRepository.GetAllArea();
                if (DataManager.CheckDs(ds, 1) && DataManager.CheckHasRow(ds.Tables[0]))
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        res.Add(new AreaViewModel()
                        {
                            Id = Convert.ToInt32(dr["Id"]),
                            Area_Code = Convert.ToInt32(dr["Area_Code"]),
                            Parent_Id = Convert.ToInt32(dr["Parent_Id"]),
                            Area_Name = dr["Area_Name"].ToString()
                        });
                    }
                }
                return res;
            },9999);
            return result;
        }
    }
}
